package ch.zbw.swt.sysventory.network.scan;

import java.util.ArrayList;
import java.util.List;

import ch.zbw.swt.sysventory.hibernate.entity.Computer;
import ch.zbw.swt.sysventory.hibernate.entity.Software;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

/**
 * Diese Classe Listet die installierten Softwarepakete unter Verwendung des
 * WMI-Interfaces auf
 * 
 * @author Silvan
 */

public class ScanSoftwares {

	// Initialise Object Data types
	private List<Software> softwares;
	private Computer computer;

	// Constructor
	public ScanSoftwares(Computer computer) {
		// Create Listobject
		this.softwares = new ArrayList<Software>();
		this.computer = computer;
	}

	// Get Software
	public List<Software> getSoftware(String host) {
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM win32_Product";
		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;

			while (enumVariant.hasMoreElements()) {

				item = enumVariant.nextElement().toDispatch();

				String stNameSoftware = Dispatch.call(item, "Caption")
						.toString();
				String stVersionSoftware = Dispatch.call(item, "Version")
						.toString();

				Software software = new Software(stNameSoftware,
						stVersionSoftware, computer);
				softwares.add(software);
			}
		} catch (Exception e) {

		}
		return softwares;
	}
}
